package com.leyou.item.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.bo.SpuBo;
import com.leyou.item.mapper.GoodsMapper;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.StockMapper;
import com.leyou.item.pojo.*;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryService;
import com.leyou.item.service.GoodsService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class GoodsServiceImpl implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private SpuDetailMapper spuDetailsMapper;
    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    private Logger logger = LoggerFactory.getLogger(GoodsService.class);

    /**
     * 分页查询，查询spu
     *
     * @param key
     * @param saleable
     * @param page
     * @param rows
     * @return
     */
    @Override
    public PageResult<SpuBo> querySpuByPage(String key, Boolean saleable, Integer page, Integer rows) {
        PageHelper.startPage(page, rows);
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        //动态查询sqlkey不为空根据key查询
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("title", "%" + key + "%");
        }
        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }
        //执行查询并统计
        Page<Spu> spus = (Page<Spu>) goodsMapper.selectByExample(example);
        //把查询到的spu转为spubo


        //用来存放spubo
        List<SpuBo> spuBos = new ArrayList<>();
        //获取查询到的结果中所有的spu

        List<Spu> spuList = spus.getResult();


        spuList.forEach(spu -> {
            SpuBo spuBo = new SpuBo();
            //对应属性拷贝，如果source中没有这个属性，则target不可能有值（source，target）
            BeanUtils.copyProperties(spu, spuBo);

            //多了cname和bname属性，所以要处理
            //拿到了分类的id ，但是却分类的名字，所以需要根据id查询名称
            // 2、查询spu的商品分类名称,要查三级分类
            List<String> names = this.categoryService.queryNamesByIds(
                    Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            //把查询到的分类的集合名称通过join转化为字符串，赋值给cname
            spuBo.setCname(StringUtils.join(names, "/"));

            Brand brand = brandService.queryBrandById(spu.getBrandId());

            //根据品牌的id查询品牌对象，并获取名称
            spuBo.setBname(brand.getName());
            spuBos.add(spuBo);
        });


        //把查询的结果整合到pageResult中
        return new PageResult<>(spus.getTotal(), new Long(spus.getPages()), spuBos);
    }

    @Transactional
    @Override
    public void saveGoods(SpuBo spuBo) {
        //缺失了4各属性
        spuBo.setSaleable(true);
        spuBo.setValid(true);
        spuBo.setCreateTime(new Date());
        spuBo.setLastUpdateTime(spuBo.getCreateTime());
        //直接保存spu并回显id
        goodsMapper.insertSelective(spuBo);

        //保存spuDetil,由于缺失spuid，所以加入id
        SpuDetail spuDetail = spuBo.getSpuDetail();
        spuDetail.setSpuId(spuBo.getId());

        spuDetailsMapper.insertSelective(spuDetail);

        //保存sku
        List<Sku> skus = spuBo.getSkus();
        saveSkus(spuBo, skus);

        sendMessage(spuBo.getId(), "insert");


    }

    private void saveSkus(SpuBo spuBo, List<Sku> skus) {
        //迭代sku集合保存
        skus.forEach(sku -> {
            sku.setSpuId(spuBo.getId());
            sku.setCreateTime(new Date());
            sku.setLastUpdateTime(spuBo.getCreateTime());

            //保存sku并回显id
            skuMapper.insertSelective(sku);
            //同时保存库存
            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());

            //保存库存
            stockMapper.insertSelective(stock);
        });
    }

    @Override
    public SpuDetail querySpuDetailById(Long spuId) {
        return spuDetailsMapper.selectByPrimaryKey(spuId);
    }

    /**
     * 由于spu的id不是sku的主键，所以做属性查询
     *
     * @param spuId
     * @return
     */
    @Override
    public List<Sku> querySkuBySpuId(Long spuId) {

        Sku record = new Sku();
        record.setSpuId(spuId);
        List<Sku> skus = skuMapper.select(record);

        //同时要查询每个sku库存
        skus.forEach(sku -> {

            //sku的id就是库存stock的主键
            sku.setStock(stockMapper.selectByPrimaryKey(sku.getId()).getStock());
        });
        return skus;
    }

    @Transactional
    @Override
    public void updateGoods(SpuBo spuBo) {
        //spu,spuDetail 可以直接更新
        spuBo.setLastUpdateTime(new Date());
        goodsMapper.updateByPrimaryKeySelective(spuBo);

        //
        spuDetailsMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());
        //先删除当前spu对应的sku，然后重新添加
        //先查，再根据查询结果删除
        Sku record = new Sku();
        record.setSpuId(spuBo.getId());
        List<Sku> skus = skuMapper.select(record);
        //根据sku信息，删除对应数据库中的信息
        skus.forEach(sku -> skuMapper.delete(sku));

        skus = null;//java垃圾处理机制，节约资源
        //循环添加sku
        saveSkus(spuBo, spuBo.getSkus());
        sendMessage(spuBo.getId(), "update");
        //


    }

    @Override
    public Spu querySpuById(Long id) {
        return goodsMapper.selectByPrimaryKey(id);
    }


    /**
     * 发送消息的方法，id就是spuIdtype就是操作类型
     *
     * @param id
     * @param type
     */
    private void sendMessage(Long id, String type) {
        // 发送消息
        try {
            this.amqpTemplate.convertAndSend("item." + type, id);
        } catch (Exception e) {
            logger.error("{}商品消息发送异常，商品id：{}", type, id, e);
        }
    }
}
